package com.cykj.user.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cykj.common.dto.ResponseDTO;
import com.cykj.common.utils.SnowflakeUtil;
import com.cykj.user.config.AlipayConfig;
import com.cykj.user.service.IOrderService;
import com.cykj.user.vo.OrdersVO;
import com.cykj.user.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @BelongsProject: smart_recruit_backend
 * @BelongsPackage: com.cykj.user.controller
 * @Author: 浮行
 * @CreateTime: 2025-08-23 10:21
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {
    // 支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";
    @Autowired
    private SnowflakeUtil snowflakeUtil;

    @Resource
    private AlipayConfig alipayConfig;
    @Autowired
    private IOrderService orderService;

    @GetMapping("/pay")
    @Operation(summary = "获取,支付金额,用户id")
    @Parameters({
            @Parameter(name = "userId",description = "用户id",required = true,in = ParameterIn.QUERY),
            @Parameter(name = "buyDuration",description = "购买会员时长",required = true,in = ParameterIn.QUERY),
            @Parameter(name = "amount",description = "支付金额",required = true,in = ParameterIn.QUERY)
    })
    public void pay(
                    @RequestParam("buyDuration") Integer buyDuration,   // 购买时长
                    @RequestParam("amount") Double amount,          // 支付金额
                    @RequestParam("userId") Integer userId,
                    HttpServletResponse httpResponse) throws Exception {

        //获取订单编号
        long orderNumber = snowflakeUtil.nextId();

        // 传递业务参数（支付成功后带回）
        JSONObject passbackParams = new JSONObject();
        passbackParams.set("buy_duration", buyDuration);
        passbackParams.set("amount", amount);
        passbackParams.set("user_id", userId);

        //创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),
                FORMAT,
                CHARSET,
                alipayConfig.getAlipayPublicKey(),
                SIGN_TYPE);
        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的 Request类
        request.setNotifyUrl(alipayConfig.getNotifyUrl()); //配置回调地址
        // 支付完成后自动跳转到本地页面的路径
        request.setReturnUrl("http://localhost:8080/#/pages/zj/PersonalCenter");

        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", orderNumber); // 预生成的订单号
        bizContent.set("total_amount", amount);
        bizContent.set("subject", "会员充值");
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.set("passback_params", passbackParams.toString()); // 传递业务参数
        request.setBizContent(bizContent.toString());
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
            // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // 直接将完整的表单html输出到页面
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    /**
    * @Description: 支付宝完成支付后返回通知完成信息 ==> 更新订单 
    * @Param: [request]
    * @return: void
    */
    @PostMapping("/notify") // 注意这里必须是POST接口
    public void payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            // 验证签名
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(
                    content,
                    sign,
                    alipayConfig.getAlipayPublicKey(),
                    "UTF-8");
            // 支付宝验签
            if (checkSignature) {
                // 2. 解析业务参数（支付请求时传递的）
                String passbackParams = params.get("passback_params");
                JSONObject bizParams = JSONUtil.parseObj(passbackParams);
                Integer buyDuration = bizParams.getInt("buy_duration");
                Double amount = bizParams.getDouble("amount");
                Integer userId = bizParams.getInt("user_id"); // 关键：解析用户ID

                // 3. 生成订单并插入数据库
                OrdersVO orderVO = new OrdersVO();
                orderVO.setOrderNumber(params.get("out_trade_no")); // 支付请求时的订单号
                orderVO.setAmount(amount);
                orderVO.setUserId(userId);
                orderVO.setBuyDuration(buyDuration);
                //调用新增订单操作
                orderService.addOrder(orderVO);

                //修改用户vip状态和会员到期时间
                UserVO userVO = new UserVO();

                userVO.setUserId(userId);

                LocalDateTime futureTime = LocalDateTime.now().plusMonths(buyDuration);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedTime = futureTime.format(formatter);
                userVO.setVipEndTime(formattedTime);

                orderService.updateUserVIP(userVO);

            }
        }
    }
    @GetMapping("/selectOrder")
    public ResponseDTO selectOrder(OrdersVO ordersVO){
        return orderService.selectUserOrders(ordersVO);
    }

}
